/**
 * 
 */
package homework6;

import java.util.LinkedList;

/**
 * @author Nican
 * 
 */
public class ValueOf implements IProc<Integer> {

	SpreadSheet spreadSheet;
	LinkedList<CellRef> usedCellRefs = new LinkedList<CellRef>();

	/**
	 * Starts a new ValueOf prodecure for the spreadsheet
	 * @param spreadSheet
	 */
	public ValueOf(SpreadSheet spreadSheet) {
		this.spreadSheet = spreadSheet;
	}

	/**
	 * Starts a new ValueOf prodecure for the spreadsheet, with the list of used cell references
	 * @param spreadSheet2
	 * @param usedCellRefs2
	 */
	public ValueOf(SpreadSheet spreadSheet, LinkedList<CellRef> usedCellRefs) {
		this(spreadSheet);
		this.usedCellRefs = usedCellRefs;
	}
	
	/**
	 * Just returns the value of the cell
	 */
	public Integer processNum(Num n) {
		return n.value;
	}
	
	/**
	 * Processes the cellreference, by looking it up in the spreadsheet, and returning the value
	 */
	public Integer processCellRef(CellRef c) {

		if (usedCellRefs.contains(c))
			throw new RuntimeException("Cellref used twice in operation!");

		usedCellRefs.add(c);
		
		Integer value = c.getValue(this.spreadSheet, usedCellRefs);

		usedCellRefs.remove(c);
		
		return value;
		
	}
	
	/**
	 * Sums two values
	 */
	public Integer processPlus(Integer leftres, Integer rightres) {
		return leftres + rightres;
	}

}